iT邦幫忙

2025 iThome 鐵人賽

1

https://ithelp.ithome.com.tw/upload/images/20260111/20177944rlFtKiiJai.jpg

https://ithelp.ithome.com.tw/upload/images/20260111/20177944HdEbtU0Zol.jpg

https://ithelp.ithome.com.tw/upload/images/20260111/201779447UYSKIFOYE.jpg

https://ithelp.ithome.com.tw/upload/images/20260111/20177944YoPGqTSlB5.jpg

https://ithelp.ithome.com.tw/upload/images/20260111/20177944PBoMRLRcIB.jpg

https://ithelp.ithome.com.tw/upload/images/20260111/20177944vaU1KIvaA8.jpg

https://ithelp.ithome.com.tw/upload/images/20260111/201779447aeCAqT3jB.jpg

#include <vector> // 378. O(Nlog(R−L)) O(1)
using namespace std;

class Solution {
public:
    int kthSmallest(vector<vector<int>>& matrix, int k){
        int n = (int)matrix.size();
        int L = matrix[0][0], R = matrix[n - 1][n - 1];

        auto countLE = [&](int x){
            int i = n - 1, j = 0, cnt = 0;
            while (i >= 0 && j < n) {
                if(matrix[i][j] <= x){
                    cnt += i + 1;
                    ++j;
                } else{
                    --i;
                }
            }
            return cnt;
        };
        
        while (L < R){
            int m = L + (R - L) / 2;
            if (countLE(m) >= k) R = m;
            else L = m + 1;
        }
        return L;
    }
};

上一篇
I have memorized 410 龜速與停滯 再調整看看吧
系列文
轉職仔之Data Science and ai master後的持續精進技術之路36
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
kawa0710
iT邦研究生 3 級 ‧ 2026-01-13 09:43:09

真猛!好久沒看到手寫code + 行號,學習雖然費時但札實。
加油!

我要留言

立即登入留言